/**
 * Created by Ysssssss on 2021/4/26.
 */

import React, { PureComponent } from 'react'
import {connect} from "react-redux";
import { withRouter } from 'react-router-dom'
import dayjs from "dayjs";
import { Select, Tabs, Button } from "antd";
import {getQuery, handleQueryEqual, setQuery} from "@utils/setUrlQuery";
import {
    getShoppingMallAfterSalesOrderList,
    refundOrder,
    refundOrderAgain
} from "@sagas/shoppingMall/shoppingMallOrder";
import {
    SHOPPING_MALL_AFTER_SALES_STATUS_CODE,
    SHOPPING_MALL_AFTER_SALES_STATUS_STR, SHOPPING_MALL_REFUND_TYPE,
    SHOPPING_MALL_REFUND_TYPE_LIST,
} from "@constants/ShoppingMallOrderStatus";
import DateRangePicker from "@common/presentational/DateRangePicker";
import ParamsInput from "@common/presentational/ParamsInput";
import CustomizeTableProvide, {
    CustomizeOrderTable,
    CustomizeTablePagination
} from "@common/presentational/CustomizeTable";
import DoubleCheck from "@common/presentational/DoubleCheck";
import ShoppingMallRefundRejectReasonModal from "@components/shoppingMall/modal/ShoppingMallRefundRejectReasonModal";
import {priceFenToYuan} from "@utils/priceConversion";

@connect(({ shoppingMallOrder }) => ({
    afterSalesOrderListMap: shoppingMallOrder.afterSalesOrderListMap
}), {
    getShoppingMallAfterSalesOrderList,
    refundOrder,
    refundOrderAgain
})
@withRouter
class ShoppingMallAfterSalesOrderPage extends PureComponent {
    constructor(props) {
        super(props);
        const {
            startDate = dayjs().subtract(3, 'month').format('YYYY-MM-DD'),
            endDate = dayjs().format('YYYY-MM-DD'),
            type = 0,
            orderNo = '',
            applyNo = '',
            category = 0,
        } = getQuery(props.history)
        this.state = {
            startDate,
            endDate,
            type,
            orderNo,
            applyNo,
            category,
        }

        this.tableRef = React.createRef()
        this.shoppingMallRefundRejectReasonModalRef = React.createRef()
        this.getTableInfo = this.getTableInfo.bind(this)

        this.columns = [{
            dataIndex: 'type',
            key: 'type',
            render: text => SHOPPING_MALL_REFUND_TYPE[text]
        }, {
            dataIndex: 'status',
            key: 'status',
            render: text => SHOPPING_MALL_AFTER_SALES_STATUS_STR[text] || '--'
        }, {
            dataIndex: 'amount',
            key: 'amount',
            render: text => priceFenToYuan(text)
        }, {
            dataIndex: 'status',
            key: 'operation',
            width: '120px',
            render: (text, record) => this.renderListOperation(record)
        }]
        this.titleLineRender = data => (
            <>
                <span>退款编号：{data.apply_number}</span>
                <span>申请时间：{data.apply_time}</span>
            </>
        )
    }

    renderListOperation = (record) => {
        switch(record.status) {
            case SHOPPING_MALL_AFTER_SALES_STATUS_CODE['applying']:
                return (
                    <div className="flex-row-right">
                        <div className="flex-vertical-between mgr-24" style={{width: '64px'}}>
                            <DoubleCheck title="是否确认退款"
                                         onClick={this.refundOrder.bind(this, record)}
                            >
                                <Button type="primary" ghost className="button-in-table">同意</Button>
                            </DoubleCheck>
                            <Button type="danger" ghost className="button-in-table mgt-8"
                                    onClick={this.rejectRefundOrder.bind(this,record)}
                            >拒绝</Button>
                        </div>
                        <a className="row-modify-button" onClick={this.goOrderDetail.bind(this,record)}>详情</a>
                    </div>
                )
            case SHOPPING_MALL_AFTER_SALES_STATUS_CODE['failed']:
                return (
                    <div className="flex-row-right">
                        <div className="flex-vertical-between mgr-24" style={{width: '64px'}}>
                            <Button type="primary" ghost className="button-in-table"
                                    onClick={this.refundOrderAgain.bind(this, record)}
                            >退款重试</Button>
                            <DoubleCheck title="是否确认标记为退款成功"
                                         onClick={this.markRefundAsSuccess.bind(this, record)}
                            >
                                <Button type="danger" ghost className="button-in-table mgt-8">标记成功</Button>
                            </DoubleCheck>
                        </div>
                        <a className="row-modify-button" onClick={this.goOrderDetail.bind(this,record)}>详情</a>
                    </div>
                )
            default:
                return (
                    <div className="flex-row-right">
                        <a className="row-modify-button" onClick={this.goOrderDetail.bind(this,record)}>详情</a>
                    </div>
                )
        }
    }

    handleValueChange (key, value) {
        if (key === 'dateRange') {
            this.setState({
                ...value
            }, this.initTable)
            return;
        }
        this.setState({
            [key]: value
        }, this.initTable)
    }

    goOrderDetail (record) {
        const { apply_number } = record
        this.props.history.push(`/shopping-mall/after-sales/${apply_number}/detail`)
    }

    refundOrder (record) {
        this.props.refundOrder({
            applyNumber: record.apply_number,
            approve: true,
        }, () => {
            this.getTableInfo()
        })
    }

    rejectRefundOrder (record) {
        const { apply_number } = record
        this.shoppingMallRefundRejectReasonModalRef.current?.show({ applyNumber: apply_number })
    }

    refundOrderAgain (record) {
        this.props.refundOrderAgain({
            applyNumber: record.apply_number,
        }, () => {
            this.getTableInfo()
        })
    }

    markRefundAsSuccess (record) {
        this.props.refundOrderAgain({
            applyNumber: record.apply_number,
            marked: true,
        }, () => {
            this.getTableInfo()
        })
    }

    getTableInfo ({ current, pageSize } = this.paginationInfo) {
        this.paginationInfo = { current, pageSize }
        const { startDate, endDate, orderNo, applyNo, type, category } = this.state
        const params = {
            startDate,
            endDate,
            orderNo,
            applyNo,
            type,
            category,
            pageNo: current,
            pageSize,
        }
        this.props.getShoppingMallAfterSalesOrderList(params)
        this.setUrlQuery()
    }

    initTable () {
        this.tableRef.current?.initPage()
    }

    setUrlQuery () {
        const { current, pageSize } = this.paginationInfo
        const { startDate, endDate, orderNo, applyNo, type, category } = this.state
        const { history } = this.props
        let params = {
            startDate, endDate, category, orderNo, applyNo, type, current, pageSize
        }
        handleQueryEqual(params, history) || setQuery(params, history)
    }

    render () {
        const { afterSalesOrderListMap } = this.props
        const { startDate, endDate, type, category, orderNo, applyNo } = this.state
        return (
            <div className="table-scroll-container shopping-mall-page shopping-mall-order-list-page">
                <div className="table-params page-params flex-vertical-center mgb-16">
                    <Select
                        style={{width: '140px'}}
                        onChange={this.handleValueChange.bind(this, 'type')}
                        value={type}
                    >
                        <Select.Option
                            value={0}
                        >
                            全部
                        </Select.Option>
                        { SHOPPING_MALL_REFUND_TYPE_LIST.map(applyType => (
                            <Select.Option
                                key={applyType.id}
                                value={applyType.id}
                            >
                                { applyType.name }
                            </Select.Option>
                        )) }
                    </Select>
                    <DateRangePicker
                        className="mgl-16"
                        startDate={startDate}
                        endDate={endDate}
                        onChange={this.handleValueChange.bind(this, 'dateRange')}
                        beforeNow
                    />
                    <ParamsInput
                        className="mgl-16"
                        style={{width: '140px'}}
                        value={applyNo}
                        onChange={this.handleValueChange.bind(this, 'applyNo')}
                        placeholder="退款编号"
                    />
                    <ParamsInput
                        className="mgl-16"
                        style={{width: '140px'}}
                        value={orderNo}
                        onChange={this.handleValueChange.bind(this, 'orderNo')}
                        placeholder="关联订单号"
                    />
                    <Tabs className="mgt-8 w-100"
                          activeKey={`${category}`}
                          onChange={this.handleValueChange.bind(this, 'category')}
                    >
                        { [{
                            id: 0,
                            name: '全部'
                        }, {
                            id: 1,
                            name: '待处理'
                        }, {
                            id: 2,
                            name: '退款成功'
                        }, {
                            id: 3,
                            name: '已拒绝'
                        }, {
                            id: 4,
                            name: '已关闭'
                        }].map(applyType => (
                            <Tabs.TabPane tab={applyType.name} key={`${applyType.id}`}/>
                        )) }
                    </Tabs>
                </div>
                <CustomizeTableProvide ref={this.tableRef} tableKey="shoppingMallAfterSalesOrderList" onChange={this.getTableInfo}>
                    <div className="table-list">
                        <CustomizeOrderTable
                            columns={this.columns}
                            dataSource={afterSalesOrderListMap.applies || []}
                            pagination
                            titleLineRender={this.titleLineRender}
                        />
                    </div>
                    <div className="table-pagination">
                        <CustomizeTablePagination
                            total={afterSalesOrderListMap.total}
                        />
                    </div>
                </CustomizeTableProvide>
                <ShoppingMallRefundRejectReasonModal
                    ref={this.shoppingMallRefundRejectReasonModalRef}
                    callback={this.getTableInfo}
                />
            </div>
        )
    }
}

export default ShoppingMallAfterSalesOrderPage